<?php
/**
 * @file ct.lists.update.php
 * @author Alejandro Dario Simi
 * @date $Date: 2013-06-05 00:31:35 +0000 (Wed, 05 Jun 2013) $
 *
 * $Id: ct.lists.update.php 69 2013-06-05 00:31:35Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/tags/wcomix-1.0-BETA1/cron/ct.lists.update.php $
 */
class WCComicsUpdateList extends WCCronTool {
	public function run($spacer = "") {
		global $wcDefaults;
		global $wcDatabaseAccess;
		global $wcTagsHolder;
		global $wcSpecialTags;
		global $wcPatterns;
		global $wcGroupsHolder;
		global $wcDirectoriesHolder;

		$db = WCConnection::Instance();
		$dbCode = md5(__FILE__);
		$dbPrefix = $wcDatabaseAccess['prefix'];
		$dirExceptions = array(
			".",
			".."
		);

		$query = "update  {$dbPrefix}comics\n";
		$query .= "set     cmc_checked = :checked,\n";
		$query .= "        cmc_lost    = 'Y'\n";
		$query .= "where   cmc_group     = :group\n";
		$query .= " and    cmc_directory = :directory\n";
		$stmtChecks = $db->prepare("{$dbCode}[1]", $query);

		$query = "insert\n";
		$query .= "        into {$dbPrefix}comics (\n";
		$query .= "                cmc_group, cmc_directory, cmc_name, cmc_size)\n";
		$query .= "        values (:group, :directory, :comic, :size)\n";
		$query .= "        on duplicate key\n";
		$query .= "                update  cmc_checked = 'Y',\n";
		$query .= "                        cmc_lost    = 'N',\n";
		$query .= "                        cmc_size    = :size\n";
		$stmtAddComic = $db->prepare("{$dbCode}[2]", $query);

		$query = "insert\n";
		$query .= "        into {$dbPrefix}directories (\n";
		$query .= "                dir_group, dir_name, dir_next_name)\n";
		$query .= "        values (:group, :name, '')\n";
		$stmtAddDirectory = $db->prepare("{$dbCode}[3]", $query);

		$query = "update  {$dbPrefix}directories\n";
		$query .= "set     dir_count  = :entries,\n";
		$query .= "        dir_dcount = :dentries\n";
		$query .= "where   dir_group = :group\n";
		$query .= " and    dir_id    = :directory\n";
		$stmtStats = $db->prepare("{$dbCode}[4]", $query);

		$query = "update  {$dbPrefix}comics\n";
		$query .= "set     cmc_lost    = 'Y'\n";
		$query .= "where   cmc_checked = 'N'\n";
		$query .= " and    cmc_lost    = 'N'\n";
		$query .= " and    dir_group = :group\n";
		$query .= " and    dir_id    = :directory\n";
		$stmtLosts = $db->prepare("{$dbCode}[5]", $query);

		// Checking every group.
		foreach($wcGroupsHolder->groups() as $group) {
			if(is_readable($group->root)) {
				echo "{$spacer}Checking group '{$group->name}' ({$group->id}):\n";

				$wcTagsHolder->createSpecialTags();

				//
				// Checking every directory.
				foreach($group->directoriesFull() as $directory) {
					$fullPath = WCSanitizer::SystemPath($directory->fullPath());
					if($directory->ok() & $directory->isChanged()) {
						echo "{$spacer}\tChecking directory '{$directory->name}': ";

						$stmtChecks->execute(array(
							":checked" => $directory->ok() ? "N" : "Y",
							":group" => $group->id,
							":directory" => $directory->id
						));

						if($directory->ok()) {
							$d = scandir($fullPath);
							$comics = array();
							$directories = array();

							// Checking every file.
							foreach($d as $entry) {
								// Checking every pattern.
								foreach($wcPatterns['comic-patterns'] as $pattern) {
									if(preg_match($pattern, $entry)) {
										$comics[] = $entry;
									} elseif(is_dir($fullPath.DIRECTORY_SEPARATOR.$entry)) {
										$tip = substr($entry, 0, 1);
										if(!in_array($entry, $dirExceptions) && ($tip != "." || $wcDefaults["allow-hiddens"])) {
											$directories[] = $entry;
										}
									}
								}
							}
							$directories = array_unique($directories);

							foreach($comics as $comic) {
								$st = stat("{$fullPath}/{$comic}");

								$stmtAddComic->execute(array(
									":group" => $group->id,
									":directory" => $directory->id,
									":comic" => $comic,
									":size" => $st['size']
								));
							}
							//
							// Checking and adding
							// directories.
							foreach($directories as $dir) {
								$name = "{$directory->name}/{$dir}";
								$name = str_replace("//", "/", $name);
								if(!$wcDirectoriesHolder->itemByName($name, $group)) {
									$stmtAddDirectory->execute(array(
										":group" => $group->id,
										":name" => $name
									));
								}
							}

							$entries = count($comics);
							$dentries = count($directories);
							echo "{$entries} comics. {$dentries} directories.";
							//
							// Updating stats.
							$stmtStats->execute(array(
								":group" => $group->id,
								":directory" => $directory->id,
								":entries" => $entries,
								":dentries" => $dentries
							));
							//
							// Updating Losts
							$stmtLosts->execute(array(
								":group" => $group->id(),
								":directory" => $directory->id
							));

							$directory->updateTimes();
						} else {
							echo WCColorText::ShellRed("directory seems to be broken");
						}

						echo "\n";
					}
				}
			}
		}
	}
	public function showHelp($spacer = "") {
		echo "{$spacer}This tool seeks for any comic in all configured directory and updates the database.\n";
		echo "{$spacer}If this tool is not used periodically, new comics won't be shown and olds may bring problems when broken.\n\n";
		echo "{$spacer}It requires no extra parameters.\n";
	}
	protected function loadOptions() {
		$this->_optionsLoaded = true;
	}
}
?>